package Service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.PageReadListener;
import entity.Customer;
import jakarta.servlet.http.HttpServletResponse;
import mapper.CustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class CustomerService {
    @Autowired
    private CustomerMapper customerMapper;//注入数据访问层


    public void addCustomer(Customer customer) {

        if(customer.getName()== null) {         //客户名称检测
            throw new IllegalArgumentException("客户名称不能为空");
        }
        Customer existing = customerMapper.selectCustomerByName(customer.getName());
        if(existing != null) {                  //客户名称查重检测
            throw new IllegalArgumentException("该名称已经存在"+customer.getName());
        }
        if(customer.getContact() == null) {         //联系人检测
            throw new IllegalArgumentException("请输入联系人");
        }
        if (!customer.getPhone().matches("/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$/\n")) {          //手机号格式检查
            throw new IllegalArgumentException("电话号码格式错误，请检查后并重新输入");
        }
        customerMapper.insertCustomer(customer);
    }


    public void updateCustomer(Customer customer) {//改
        customerMapper.updateCustomer(customer);
    }


    public void deleteCustomer(String id) {

        customerMapper.deleteCustomerById(Long.parseLong(id));
    }


    public Customer getCustomer(String id) {
        Long customerId = Long.parseLong(id);   //把id类型进行解析
        return customerMapper.selectCustomerById(customerId);
    }

    public void exportCustomer(HttpServletResponse response) throws IOException {

        List<Customer>customerList = customerMapper.selectAllCustomer();   //通过注入层，调用函数，获取所有的客户信息
        if(customerList.size() == 0||customerList == null) {
            throw new IOException("无客户数据可导出");
        }
        //将客户数据导出到excel表格
        String fileName = URLEncoder.encode("客户资料导出.xlsx", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName); //响应头

        // 使用 EasyExcel
        EasyExcel.write(response.getOutputStream(), Customer.class)
                .sheet("客户列表") // Excel 工作表名称
                .doWrite(customerList); // 将客户数据写入 Excel

    }
    public void importCustomer(MultipartFile file) throws IOException {
        List<Customer> customerList = new ArrayList<>();
        EasyExcel.read(file.getInputStream())
                .head(Customer.class)
                .registerReadListener(new PageReadListener<Customer>(dataList -> {
                    for (Customer customer : dataList) {
                        try {
                            addCustomer(customer);
                        } catch (IllegalArgumentException e) {
                            System.err.println("导入客户 " + customer.getName() + " 失败: " + e.getMessage());
                        }
                    }
                }))
                .sheet()
                .doRead();
    }
}
